package com.up.upzl.biz.bean;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.up.upzl.biz.domain.SysApp;
import com.up.upzl.biz.domain.SysRole;

import lombok.Data;

/**
 * 放入session的SysAccount对象
 * 
 * @author geeks
 *
 */
@Data
public class SysAccountInSession implements Serializable {

	private static final long serialVersionUID = -7918187836792850251L;

	/**
	 * 主键
	 */
	private Long id;

	/**
	 * 账号
	 */
	private String account;

	/**
	 * 用户名
	 */
	private String name;

	/**
	 * 用户角色
	 */
	private SysRole sysRole;

	/**
	 * 应用列表
	 */
	private List<SysApp> sysApps;

	/**
	 * 应用列表
	 * 
	 * @param sysApps
	 */
	public void setSysApps(List<SysApp> sysApps) {
		this.sysApps = sysApps;

		Map<Long, SysApp> sysAppMap = Maps.newHashMap();
		List<SysApp> sysAppsInTree = Lists.newArrayList();
		sysApps.forEach(sysApp -> {
			sysAppMap.put(sysApp.getId(), sysApp);
			sysApp.setSubSysApps(null);
		});

		sysApps.forEach(sysApp -> {
			if (sysApp.getParentId() == null) {
				sysAppsInTree.add(sysApp);
			} else {
				SysApp sysAppParent = sysAppMap.get(sysApp.getParentId());
				if (sysAppParent != null) {
					if (sysAppParent.getSubSysApps() == null) {
						List<SysApp> subSysApps = Lists.newArrayList();
						subSysApps.add(sysApp);
						sysAppParent.setSubSysApps(subSysApps);
					} else {
						sysAppParent.getSubSysApps().add(sysApp);
					}
				}
			}
		});

		this.sysAppsInTree = sysAppsInTree;
	}

	/**
	 * 应用列表
	 */
	private List<SysApp> sysAppsInTree;

	/**
	 * 应用列表
	 */
	private Set<String> appActions;

	/**
	 * 获取应用列表
	 * 
	 * @return 应用列表
	 */
	public Set<String> getAppActions() {
		if (appActions == null) {
			appActions = sysApps.stream().map(sysApp -> sysApp.getAppAction()).collect(Collectors.toSet());
		}
		return appActions;
	}
}
